package com.pomelo.base.core.config;

import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.DiskStoreConfiguration;
import net.sf.ehcache.config.PersistenceConfiguration;
import net.sf.ehcache.config.PersistenceConfiguration.Strategy;

@Configuration
public class CommonConfiguration {

    @Bean(name = "ehCacheCacheManager")
    public EhCacheCacheManager EhCacheCacheManager(net.sf.ehcache.CacheManager cacheManager) {
        EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager();
        ehCacheCacheManager.setCacheManager(cacheManager);
        return ehCacheCacheManager;
    }

    @Bean(name = "cacheManager")
    public CacheManager cacheManager() {
        net.sf.ehcache.config.Configuration configuration = new net.sf.ehcache.config.Configuration();
        configuration.setName("ehcacheManager");
        DiskStoreConfiguration diskStore = new DiskStoreConfiguration();
        diskStore.setPath("java.io.tmpdir");
        configuration.diskStore(diskStore);
        CacheConfiguration cacheConfiguration = new CacheConfiguration();
        cacheConfiguration.setEternal(true);
        // 对象检测线程运行时间间隔。标识对象状态的线程多长时间运行一次。默认是120秒。（单位：秒）
        cacheConfiguration.setDiskExpiryThreadIntervalSeconds(120);
        // 缓存的3种清空策略:FIFO（先进先出）LFU（最少使用）LRU（最近最少使用）
        cacheConfiguration.setMemoryStoreEvictionPolicy("LRU");
        // persistence表示Cache的持久化，它只有一个属性strategy，表示当前Cache对应的持久化策略
        PersistenceConfiguration persistence = new PersistenceConfiguration();
        // localTempSwap当堆内存或者非堆内存里面的元素已经满了的时候，将其中的元素临时的存放在磁盘上，一旦重启就会消失。
        persistence.strategy(Strategy.LOCALTEMPSWAP);
        cacheConfiguration.persistence(persistence);
        configuration.setDefaultCacheConfiguration(cacheConfiguration);
        CacheManager cacheManager = new CacheManager(configuration);
        return cacheManager;
    }

}
